// 本地图片不通过input上传后端
function uploadFormData(formData) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open("POST", "https://puton.meidaojia.com/api/v1/test/exchangeHair");
    xhr.onload = function () {
      if (xhr.status >= 200 && xhr.status < 300) {
        try {
          resolve(JSON.parse(xhr.responseText));
        } catch (e) {
          reject("返回内容不是有效JSON");
        }
      } else {
        reject("上传失败，状态码：" + xhr.status);
      }
    };
    xhr.onerror = function () {
      reject("网络错误");
    };
    xhr.send(formData);
  });
}

// url下载到本地
const downloadFile = (url) => {
  return fetch(url).then((res) => {
    return res.blob();
  });
};

// 数字转中文
function numToChinese(num) {
  const map = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  return map[num] !== undefined ? map[num] : num;
}

function getMaxElement(arr) {
  const elements = ["金", "木", "水", "火", "土"];
  arr = arr.map(Number);
  const maxIndex = arr.indexOf(Math.max(...arr));
  return elements[maxIndex];
}

function reorderByValue(arr, target) {
  return [
    ...arr.filter((item) => item.typeName + "型" === target),
    ...arr.filter((item) => item.typeName + "型" !== target),
  ];
}
export {
  uploadFormData,
  downloadFile,
  numToChinese,
  getMaxElement,
  reorderByValue,
};
